const db = require('../db/index');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { expiresIn, secretKey } = require('../config');

exports.login = (req, res) => {
  const { username, password } = req.body;
  const sql = 'select * from ev_users where username=?';

  db.query(sql, username, (err, result) => {
    if (err) {
      res.cc(err);
      return;
    }

    if (result.length !== 1) {
      res.cc('查询失败');
      return;
    }

    // 比较用户提交的密码，跟数据库里面存储的密码的一致性
    const compareResult = bcrypt.compareSync(password, result[0].password);

    if (!compareResult) return res.cc('密码错误');

    // 获取需要打包到token的信息
    const user = { ...result[0], password: '', user_pic: '' };
    // 签发token
    const tokenStr = jwt.sign(user, secretKey, { expiresIn });
    console.log(tokenStr);

    // token返回给客户端
    res.send({
      status: 0,
      message: '登录成功',
      token: 'Bearer ' + tokenStr,
    });
  });
};

exports.regUser = (req, res) => {
  const userinfo = req.body;

  // 对表单中的数据进行合法性校验
  // localhost:3000/api/reguser
  if (!userinfo.username || !userinfo.password) {
    return res.cc('用户名和密码不正确');
  }

  const query = 'select * from ev_users where username=?';

  db.query(query, userinfo.username, (err, result) => {
    if (err) {
      res.cc(err);
      return;
    }
    console.log(result);

    if (result.length > 0) {
      res.cc('用户名占用');
      return;
    }

    userinfo.password = bcrypt.hashSync(userinfo.password, 10);

    const sql = 'insert into ev_users set ?';

    // 调用 db.query() 执行 SQL 语句
    db.query(
      sql,
      { username: userinfo.username, password: userinfo.password },
      (err, results) => {
        // 判断 sql 语句是否执行成功
        if (err) return res.send({ status: 1, message: err.message });
        // 判断影响行数是否为 1
        if (results.affectedRows !== 1)
          return res.cc('注册用户失败，请稍后再试！');
        // 注册成功
        res.cc('注册成功', 0);
      }
    );
  });
};
